//package com.wxzz.elearning.gateway.filter.pre;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.fasterxml.jackson.core.filter.TokenFilter;
//import com.wxzz.elearning.common.bean.JWTResult;
//import com.wxzz.elearning.common.utils.JWTUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cloud.gateway.config.GatewayProperties;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.cloud.gateway.route.RouteDefinition;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.data.redis.support.atomic.RedisAtomicLong;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.server.reactive.ServerHttpRequest;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.util.List;
//import java.util.concurrent.TimeUnit;
////@Component
//public class HighFrequencyAccessFilter implements GlobalFilter, Ordered {
//
//    private final Logger LOGGER = LoggerFactory.getLogger(TokenFilter.class);
//
//    @Autowired
//    private StringRedisTemplate redisTemplate;
//    @Autowired
//    private GatewayProperties gatewayProperties;
//
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        String tokenAuthorization =  request.getHeaders().getFirst("authorization");
//        String requestURL = request.getPath().value();
//        LOGGER.info("--->>> TokenFilter {},{}, {}", request.getMethod(), requestURL, tokenAuthorization);
//        if(null == requestURL || requestURL.indexOf("login") > 0){
//            return chain.filter(exchange);
//        }
//
//        List<RouteDefinition> routes = gatewayProperties.getRoutes();
//        String accessService = "";
//        for(RouteDefinition route : routes) {
//            String zuulPath = route.getPredicates().stream().filter(predicateDefinition -> predicateDefinition.getName().equals("Path")).findFirst().get().getArgs().values().stream().findFirst().get();
//            //String zuulPath = route.getPredicates();
//            zuulPath = zuulPath != null? zuulPath.substring(0, zuulPath.length()-2) : "";
//            Integer urlIndex = requestURL.indexOf(zuulPath);
//            if (urlIndex >= 0) {
//                accessService = requestURL.substring(urlIndex+zuulPath.length(), requestURL.length());
//                break;
//            }
//        }
//
//        JWTResult jwtResult = JWTUtils.validateJWT(tokenAuthorization);
//        JSONObject jsonObject = JSONObject.parseObject(jwtResult.getClaims().getSubject());
//        String phoneNumber = jsonObject.getString("phoneNumber");
//        RedisAtomicLong entityIdCounter = new RedisAtomicLong(phoneNumber + ":" + accessService + "_at", redisTemplate.getConnectionFactory());
//        entityIdCounter.expire(60, TimeUnit.SECONDS);
//        Long increment = entityIdCounter.getAndIncrement();
//        if(increment >= 30){
//            //不对其进行路由
//            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
//            return getVoidMono( exchange.getResponse());
//        }
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return 10;
//    }
//
//    private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse) {
//         serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//        JSONObject result = new JSONObject();
//        result.put("status","500");
//        result.put("message","您访问太过频繁，请稍后再试");
//         DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
//        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
//    }
//
//}
